// 终极BOSS系统 - 第20关超级变异体
(function() {
    'use strict';
    
    console.log('👹 终极BOSS系统加载...');
    
    // 终极BOSS类 - 病毒原始体
    class UltimateBoss {
        constructor(x, y, type = 'virus_origin') {
            try {
                this.x = x || 500;
                this.y = y || 200;
                this.type = type;
                this.radius = 60; // 更大的碰撞半径
                
                const stats = this.getUltimateBossStats(this.type);
                this.health = stats.health;
                this.maxHealth = this.health;
                this.speed = stats.speed;
                this.damage = stats.damage;
            
                // BOSS状态
                this.state = 'spawning'; // 'spawning', 'phase1', 'phase2', 'phase3', 'phase4', 'phase5', 'final_rage', 'dying'
                this.phase = 1; // BOSS阶段（1-6阶段）
                this.target = null;
                this.lastAttackTime = 0;
                this.attackCooldown = 1500; // 更快的攻击频率
                this.specialAttackCooldown = 3000; // 更频繁的特殊攻击
                this.lastSpecialAttack = 0;
                
                // 动画
                this.animationFrame = 0;
                this.animationTime = 0;
                this.facing = 0;
                this.size = 80; // 更大的BOSS尺寸
                
                // 终极能力
                this.canSummonAll = true; // 可以召唤所有类型僵尸
                this.canShootBarrage = true; // 弹幕攻击
                this.canCreateShockwave = true; // 震波攻击
                this.canTeleport = true; // 瞬移能力
                this.canCreateClones = true; // 创建分身
                this.canManipulateEnvironment = true; // 环境操控
                
                // 攻击模式
                this.attackModes = ['melee', 'projectile_barrage', 'shockwave', 'summon_horde', 'teleport_strike', 'clone_assault', 'meteor_rain'];
                this.currentAttackMode = 'melee';
                this.modeChangeTimer = 0;
                this.modeChangeCooldown = 8000; // 8秒换一次攻击模式
                
                // 分身系统
                this.clones = [];
                this.maxClones = 3;
                
                // 召唤小怪
                this.minions = [];
                this.maxMinions = 12; // 更多小怪
                
                // 生成动画
                this.spawnTime = Date.now();
                this.spawnDuration = 5000; // 更长的生成时间
                this.isInvulnerable = true;
                
                // 视觉效果
                this.bloodStains = [];
                this.aura = { radius: 0, color: '#8B0000', alpha: 0.5 };
                this.energyField = { radius: 120, intensity: 1.0 };
                
                // 阶段转换特效
                this.phaseTransitionActive = false;
                this.phaseTransitionDuration = 3000;
                this.phaseTransitionStartTime = 0;
                
                // 环境操控
                this.environmentEffects = [];
                this.lastEnvironmentEffect = 0;
                this.environmentEffectCooldown = 15000;
                
                console.log('终极BOSS创建:', this.type, '血量:', this.health);
            } catch (error) {
                console.error('终极BOSS构造失败:', error);
                throw error;
            }
        }
        
        getUltimateBossStats(type) {
            const stats = {
                'virus_origin': {
                    name: '病毒原始体',
                    health: 3500, // 极高血量
                    speed: 80,
                    damage: 60,
                    color: '#4B0082',
                    specialAbilities: ['summon_all', 'projectile_barrage', 'shockwave', 'teleport', 'clone', 'environment_control']
                },
                'chaos_lord': {
                    name: '混沌领主',
                    health: 4000, // 更高血量
                    speed: 90,
                    damage: 70,
                    color: '#8B0000',
                    specialAbilities: ['reality_distortion', 'time_manipulation', 'dimensional_rift']
                }
            };
            return stats[type] || stats['virus_origin'];
        }
        
        update(deltaTime, player) {
            this.updateState(deltaTime, player);
            this.updateAnimation(deltaTime);
            this.updateMinions(deltaTime, player);
            this.updateClones(deltaTime, player);
            this.updateAura(deltaTime);
            this.updateEnvironmentEffects(deltaTime);
            
            // 检查阶段切换
            this.checkPhaseTransition();
            
            // 更新攻击模式
            this.updateAttackMode(deltaTime);
        }
        
        updateState(deltaTime, player) {
            if (!player) return;
            
            const currentTime = Date.now();
            const distToPlayer = Math.sqrt(
                Math.pow(this.x - player.x, 2) + Math.pow(this.y - player.y, 2)
            );
            
            switch (this.state) {
                case 'spawning':
                    this.handleSpawning(currentTime);
                    break;
                    
                case 'phase1':
                case 'phase2':
                case 'phase3':
                case 'phase4':
                case 'phase5':
                    this.handleCombatPhase(currentTime, player, distToPlayer);
                    break;
                    
                case 'final_rage':
                    this.handleFinalRage(currentTime, player, distToPlayer);
                    break;
                    
                case 'dying':
                    this.handleDeath(deltaTime);
                    break;
            }
        }
        
        handleSpawning(currentTime) {
            if (currentTime - this.spawnTime > this.spawnDuration) {
                this.state = 'phase1';
                this.isInvulnerable = false;
                
                // 生成震撼效果
                this.createSpawnEffect();
                
                console.log('👹 终极BOSS生成完成，第1阶段开始！');
            }
        }
        
        handleCombatPhase(currentTime, player, distToPlayer) {
            // 根据当前攻击模式执行相应行为
            switch (this.currentAttackMode) {
                case 'melee':
                    this.meleeMode(currentTime, player, distToPlayer);
                    break;
                case 'projectile_barrage':
                    this.projectileBarrageMode(currentTime, player);
                    break;
                case 'shockwave':
                    this.shockwaveMode(currentTime, player);
                    break;
                case 'summon_horde':
                    this.summonHordeMode(currentTime);
                    break;
                case 'teleport_strike':
                    this.teleportStrikeMode(currentTime, player);
                    break;
                case 'clone_assault':
                    this.cloneAssaultMode(currentTime);
                    break;
                case 'meteor_rain':
                    this.meteorRainMode(currentTime, player);
                    break;
            }
            
            // 环境操控
            if (currentTime - this.lastEnvironmentEffect > this.environmentEffectCooldown) {
                this.createEnvironmentEffect();
                this.lastEnvironmentEffect = currentTime;
            }
        }
        
        handleFinalRage(currentTime, player, distToPlayer) {
            // 最终阶段：所有能力同时使用，极度危险
            this.speed *= 1.5;
            this.attackCooldown *= 0.5;
            this.specialAttackCooldown *= 0.3;
            
            // 疯狂攻击模式
            if (currentTime - this.lastAttackTime > this.attackCooldown) {
                this.performFinalRageAttack(player);
                this.lastAttackTime = currentTime;
            }
        }
        
        // 近战模式
        meleeMode(currentTime, player, distToPlayer) {
            if (distToPlayer > 150) {
                this.moveTowardsPlayer(player, 0.016);
            } else if (currentTime - this.lastAttackTime > this.attackCooldown) {
                this.performMeleeAttack(player);
                this.lastAttackTime = currentTime;
            }
        }
        
        // 弹幕模式
        projectileBarrageMode(currentTime, player) {
            if (currentTime - this.lastAttackTime > 300) { // 快速连射
                this.shootProjectileBarrage(player);
                this.lastAttackTime = currentTime;
            }
        }
        
        // 震波模式
        shockwaveMode(currentTime, player) {
            if (currentTime - this.lastSpecialAttack > 2000) {
                this.createShockwave();
                this.lastSpecialAttack = currentTime;
            }
        }
        
        // 召唤群体模式
        summonHordeMode(currentTime) {
            if (currentTime - this.lastSpecialAttack > 5000 && this.minions.length < this.maxMinions) {
                this.summonZombieHorde();
                this.lastSpecialAttack = currentTime;
            }
        }
        
        // 瞬移打击模式
        teleportStrikeMode(currentTime, player) {
            if (currentTime - this.lastSpecialAttack > 4000) {
                this.performTeleportStrike(player);
                this.lastSpecialAttack = currentTime;
            }
        }
        
        // 分身突击模式
        cloneAssaultMode(currentTime) {
            if (currentTime - this.lastSpecialAttack > 6000 && this.clones.length < this.maxClones) {
                this.createClone();
                this.lastSpecialAttack = currentTime;
            }
        }
        
        // 流星雨模式
        meteorRainMode(currentTime, player) {
            if (currentTime - this.lastSpecialAttack > 3000) {
                this.createMeteorRain(player);
                this.lastSpecialAttack = currentTime;
            }
        }
        
        // 更新攻击模式
        updateAttackMode(deltaTime) {
            this.modeChangeTimer += deltaTime;
            
            if (this.modeChangeTimer >= this.modeChangeCooldown) {
                this.changeAttackMode();
                this.modeChangeTimer = 0;
            }
        }
        
        changeAttackMode() {
            const availableModes = this.attackModes.filter(mode => mode !== this.currentAttackMode);
            this.currentAttackMode = availableModes[Math.floor(Math.random() * availableModes.length)];
            
            console.log(`👹 BOSS切换攻击模式: ${this.currentAttackMode}`);
            this.createModeChangeEffect();
        }
        
        // 移动向玩家
        moveTowardsPlayer(player, deltaTime) {
            const dx = player.x - this.x;
            const dy = player.y - this.y;
            const distance = Math.sqrt(dx * dx + dy * dy);
            
            if (distance > 0) {
                const dirX = dx / distance;
                const dirY = dy / distance;
                
                this.x += dirX * this.speed * deltaTime;
                this.y += dirY * this.speed * deltaTime;
                this.facing = Math.atan2(dy, dx);
            }
        }
        
        // 近战攻击
        performMeleeAttack(player) {
            console.log('👹 终极BOSS近战攻击！');
            this.createMeleeAttackEffect();
            
            // 范围伤害，更大的攻击范围
            const attackRange = 100;
            const distance = Math.sqrt(
                Math.pow(this.x - player.x, 2) + Math.pow(this.y - player.y, 2)
            );
            
            if (distance <= attackRange && player.takeDamage) {
                player.takeDamage(this.damage);
            }
        }
        
        // 弹幕攻击
        shootProjectileBarrage(player) {
            try {
                const numProjectiles = 8 + this.phase * 2; // 根据阶段增加弹数
                
                for (let i = 0; i < numProjectiles; i++) {
                    const angle = (Math.PI * 2 / numProjectiles) * i + Math.random() * 0.5;
                    
                    const projectile = new UltimateBossProjectile(
                        this.x, this.y,
                        Math.cos(angle) * 300,
                        Math.sin(angle) * 300,
                        this.damage * 0.8,
                        'barrage'
                    );
                    
                    if (window.gameEngine) {
                        window.gameEngine.bossProjectiles = window.gameEngine.bossProjectiles || [];
                        window.gameEngine.bossProjectiles.push(projectile);
                    }
                }
                
                console.log(`👹 BOSS发射${numProjectiles}发弹幕！`);
            } catch (error) {
                console.error('弹幕攻击失败:', error);
            }
        }
        
        // 震波攻击
        createShockwave() {
            console.log('👹 BOSS创建震波攻击！');
            
            try {
                if (window.gameEngine) {
                    // 创建多重震波
                    for (let i = 1; i <= 3; i++) {
                        setTimeout(() => {
                            const shockwave = new Shockwave(this.x, this.y, i * 80, this.damage * 0.6);
                            if (!window.gameEngine.shockwaves) {
                                window.gameEngine.shockwaves = [];
                            }
                            window.gameEngine.shockwaves.push(shockwave);
                        }, i * 500);
                    }
                }
                
                this.createShockwaveEffect();
            } catch (error) {
                console.error('震波攻击失败:', error);
            }
        }
        
        // 召唤僵尸群体
        summonZombieHorde() {
            try {
                console.log('👹 BOSS召唤僵尸群体！');
                const summonCount = 4 + this.phase;
                
                // 所有可用的僵尸类型，包括新类型
                const allZombieTypes = ['normal', 'fast', 'tank', 'spitter', 'exploder', 'electric', 'stealth', 'giant', 'splitter', 'healer', 'berserker'];
                
                for (let i = 0; i < summonCount; i++) {
                    const angle = (Math.PI * 2 / summonCount) * i;
                    const distance = 120;
                    const minionX = this.x + Math.cos(angle) * distance;
                    const minionY = this.y + Math.sin(angle) * distance;
                    
                    // 根据阶段选择更强的僵尸类型
                    let zombieType;
                    if (this.phase <= 2) {
                        zombieType = allZombieTypes[Math.floor(Math.random() * 4)]; // 基础类型
                    } else if (this.phase <= 4) {
                        zombieType = allZombieTypes[Math.floor(Math.random() * 8)]; // 包含一些新类型
                    } else {
                        zombieType = allZombieTypes[Math.floor(Math.random() * allZombieTypes.length)]; // 所有类型
                    }
                    
                    if (typeof Zombie !== 'undefined') {
                        const minion = new Zombie(minionX, minionY, zombieType, Math.min(this.phase + 1, 5));
                        
                        // BOSS召唤的小怪更强
                        minion.health = Math.floor(minion.health * 1.5);
                        minion.maxHealth = minion.health;
                        minion.damage = Math.floor(minion.damage * 1.3);
                        minion.isBossMinion = true;
                        
                        this.minions.push(minion);
                        
                        if (window.gameEngine && window.gameEngine.zombies) {
                            window.gameEngine.zombies.push(minion);
                        }
                    }
                }
                
                this.createSummonEffect();
            } catch (error) {
                console.error('召唤僵尸群体失败:', error);
            }
        }
        
        // 瞬移打击
        performTeleportStrike(player) {
            console.log('👹 BOSS瞬移打击！');
            
            // 瞬移到玩家附近
            const angle = Math.random() * Math.PI * 2;
            const distance = 80;
            
            this.createTeleportEffect(this.x, this.y); // 原位置特效
            
            this.x = player.x + Math.cos(angle) * distance;
            this.y = player.y + Math.sin(angle) * distance;
            
            this.createTeleportEffect(this.x, this.y); // 新位置特效
            
            // 瞬移后立即攻击
            setTimeout(() => {
                this.performMeleeAttack(player);
            }, 200);
        }
        
        // 创建分身
        createClone() {
            console.log('👹 BOSS创建分身！');
            
            try {
                const clone = new UltimateBossClone(
                    this.x + (Math.random() - 0.5) * 200,
                    this.y + (Math.random() - 0.5) * 200,
                    this
                );
                
                this.clones.push(clone);
                
                if (window.gameEngine) {
                    if (!window.gameEngine.bossClones) {
                        window.gameEngine.bossClones = [];
                    }
                    window.gameEngine.bossClones.push(clone);
                }
                
                this.createCloneEffect();
            } catch (error) {
                console.error('创建分身失败:', error);
            }
        }
        
        // 流星雨
        createMeteorRain(player) {
            console.log('👹 BOSS召唤流星雨！');
            
            try {
                const meteorCount = 6 + this.phase;
                
                for (let i = 0; i < meteorCount; i++) {
                    setTimeout(() => {
                        const targetX = player.x + (Math.random() - 0.5) * 300;
                        const targetY = player.y + (Math.random() - 0.5) * 300;
                        
                        const meteor = new Meteor(targetX, targetY, this.damage * 0.7);
                        
                        if (window.gameEngine) {
                            if (!window.gameEngine.meteors) {
                                window.gameEngine.meteors = [];
                            }
                            window.gameEngine.meteors.push(meteor);
                        }
                    }, i * 500);
                }
            } catch (error) {
                console.error('流星雨失败:', error);
            }
        }
        
        // 最终阶段攻击
        performFinalRageAttack(player) {
            // 同时使用多种攻击方式
            this.shootProjectileBarrage(player);
            
            setTimeout(() => {
                this.createShockwave();
            }, 500);
            
            setTimeout(() => {
                if (this.minions.length < this.maxMinions) {
                    this.summonZombieHorde();
                }
            }, 1000);
        }
        
        // 环境操控
        createEnvironmentEffect() {
            const effects = ['poison_cloud', 'electric_field', 'gravity_well', 'time_distortion'];
            const effect = effects[Math.floor(Math.random() * effects.length)];
            
            console.log(`👹 BOSS创建环境效果: ${effect}`);
            
            try {
                const environmentEffect = new EnvironmentEffect(
                    Math.random() * 800 + 100,
                    Math.random() * 600 + 100,
                    effect,
                    10000 // 10秒持续时间
                );
                
                this.environmentEffects.push(environmentEffect);
                
                if (window.gameEngine) {
                    if (!window.gameEngine.environmentEffects) {
                        window.gameEngine.environmentEffects = [];
                    }
                    window.gameEngine.environmentEffects.push(environmentEffect);
                }
            } catch (error) {
                console.error('创建环境效果失败:', error);
            }
        }
        
        // 受伤
        takeDamage(damage) {
            if (this.isInvulnerable || this.phaseTransitionActive) return;
            
            this.health -= damage;
            this.addBloodStain();
            
            // 显示伤害数字
            this.showDamageNumber(damage);
            
            if (this.health <= 0) {
                this.die();
            }
        }
        
        // 死亡
        die() {
            this.state = 'dying';
            
            // 创建史诗级死亡特效
            this.createEpicDeathEffect();
            
            console.log('👹 终极BOSS被击败！史诗级胜利！');
        }
        
        // 检查阶段转换
        checkPhaseTransition() {
            const healthPercent = this.health / this.maxHealth;
            let newPhase = this.phase;
            
            if (healthPercent < 0.85 && this.phase === 1) {
                newPhase = 2;
            } else if (healthPercent < 0.7 && this.phase === 2) {
                newPhase = 3;
            } else if (healthPercent < 0.55 && this.phase === 3) {
                newPhase = 4;
            } else if (healthPercent < 0.4 && this.phase === 4) {
                newPhase = 5;
            } else if (healthPercent < 0.25 && this.phase === 5) {
                newPhase = 6;
                this.state = 'final_rage';
            }
            
            if (newPhase !== this.phase) {
                this.startPhaseTransition(newPhase);
            }
        }
        
        // 开始阶段转换
        startPhaseTransition(newPhase) {
            console.log(`👹 BOSS进入第${newPhase}阶段！`);
            
            this.phase = newPhase;
            this.phaseTransitionActive = true;
            this.phaseTransitionStartTime = Date.now();
            this.isInvulnerable = true;
            
            // 阶段强化
            this.enhanceForPhase(newPhase);
            
            // 阶段转换特效
            this.createPhaseTransitionEffect();
            
            // 结束无敌状态
            setTimeout(() => {
                this.phaseTransitionActive = false;
                this.isInvulnerable = false;
            }, this.phaseTransitionDuration);
        }
        
        // 阶段强化
        enhanceForPhase(phase) {
            const enhancement = 1 + (phase - 1) * 0.15; // 每阶段增强15%
            
            this.speed = Math.floor(this.speed * enhancement);
            this.damage = Math.floor(this.damage * enhancement);
            this.attackCooldown = Math.floor(this.attackCooldown * 0.9); // 攻击速度提升
            this.specialAttackCooldown = Math.floor(this.specialAttackCooldown * 0.85);
            
            console.log(`👹 阶段${phase}强化完成！速度: ${this.speed}, 伤害: ${this.damage}`);
        }
        
        // 各种特效方法（简化版）
        createSpawnEffect() {
            this.createParticleExplosion(50, '#4B0082', 300);
        }
        
        createMeleeAttackEffect() {
            this.createParticleExplosion(20, '#FF4500', 150);
        }
        
        createShockwaveEffect() {
            this.createParticleExplosion(30, '#FFD700', 200);
        }
        
        createSummonEffect() {
            this.createParticleExplosion(25, '#800080', 180);
        }
        
        createTeleportEffect(x, y) {
            this.createParticleExplosionAt(x, y, 15, '#00FFFF', 120);
        }
        
        createCloneEffect() {
            this.createParticleExplosion(20, '#9370DB', 160);
        }
        
        createModeChangeEffect() {
            this.createParticleExplosion(15, '#FF6347', 100);
        }
        
        createPhaseTransitionEffect() {
            this.createParticleExplosion(40, '#FFD700', 250);
        }
        
        createEpicDeathEffect() {
            // 多重爆炸效果
            for (let i = 0; i < 5; i++) {
                setTimeout(() => {
                    this.createParticleExplosion(60, ['#FF0000', '#FFD700', '#FF4500', '#DC143C'][i % 4], 400);
                }, i * 500);
            }
        }
        
        // 通用粒子爆炸效果
        createParticleExplosion(count, color, speed) {
            this.createParticleExplosionAt(this.x, this.y, count, color, speed);
        }
        
        createParticleExplosionAt(x, y, count, color, speed) {
            try {
                if (window.gameEngine && window.gameEngine.particles) {
                    for (let i = 0; i < count; i++) {
                        const angle = (Math.PI * 2 * i) / count;
                        const particleSpeed = Math.random() * speed + speed * 0.5;
                        
                        window.gameEngine.particles.push({
                            x: x,
                            y: y,
                            vx: Math.cos(angle) * particleSpeed,
                            vy: Math.sin(angle) * particleSpeed,
                            life: Math.random() * 3 + 2,
                            maxLife: Math.random() * 3 + 2,
                            color: Array.isArray(color) ? color[Math.floor(Math.random() * color.length)] : color,
                            size: Math.random() * 8 + 4
                        });
                    }
                }
            } catch (error) {
                console.error('创建粒子爆炸失败:', error);
            }
        }
        
        // 更新各种系统
        updateMinions(deltaTime, player) {
            this.minions = this.minions.filter(minion => minion.health > 0);
        }
        
        updateClones(deltaTime, player) {
            this.clones = this.clones.filter(clone => clone.health > 0);
        }
        
        updateAnimation(deltaTime) {
            this.animationTime += deltaTime;
            if (this.animationTime > 150) { // 更快的动画
                this.animationFrame = (this.animationFrame + 1) % 12;
                this.animationTime = 0;
            }
        }
        
        updateAura(deltaTime) {
            this.aura.radius = 80 + Math.sin(Date.now() * 0.008) * 20;
            this.energyField.intensity = 0.8 + Math.sin(Date.now() * 0.01) * 0.3;
        }
        
        updateEnvironmentEffects(deltaTime) {
            this.environmentEffects = this.environmentEffects.filter(effect => 
                Date.now() - effect.startTime < effect.duration
            );
        }
        
        addBloodStain() {
            // 血迹效果已禁用
            return;
        }
        
        showDamageNumber(damage) {
            try {
                if (window.gameEngine && window.gameEngine.floatingTexts) {
                    window.gameEngine.floatingTexts.push({
                        x: this.x + (Math.random() - 0.5) * 40,
                        y: this.y - 20,
                        text: `-${damage}`,
                        color: '#FF0000',
                        fontSize: 18,
                        life: 2000,
                        vx: (Math.random() - 0.5) * 50,
                        vy: -Math.random() * 100 - 50
                    });
                }
            } catch (error) {
                console.error('显示伤害数字失败:', error);
            }
        }
        
        // 渲染方法
        render(ctx) {
            ctx.save();
            ctx.translate(this.x, this.y);
            
            // 绘制能量场
            this.drawEnergyField(ctx);
            
            // 绘制光环
            this.drawAura(ctx);
            
            // 绘制BOSS
            this.drawUltimateBoss(ctx);
            
            // 绘制血量条
            this.drawBossHealthBar(ctx);
            
            // 绘制阶段指示器
            this.drawPhaseIndicator(ctx);
            
            // 绘制状态效果
            this.drawStatusEffects(ctx);
            
            ctx.restore();
        }
        
        drawEnergyField(ctx) {
            const time = Date.now() * 0.005;
            
            for (let i = 0; i < 3; i++) {
                const radius = this.energyField.radius + i * 20;
                const alpha = (0.2 + Math.sin(time + i) * 0.1) * this.energyField.intensity;
                
                ctx.globalAlpha = alpha;
                ctx.strokeStyle = this.phase <= 3 ? '#4B0082' : '#8B0000';
                ctx.lineWidth = 3;
                ctx.beginPath();
                ctx.arc(0, 0, radius, 0, Math.PI * 2);
                ctx.stroke();
            }
            
            ctx.globalAlpha = 1;
        }
        
        drawAura(ctx) {
            ctx.globalAlpha = this.aura.alpha;
            
            const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, this.aura.radius);
            gradient.addColorStop(0, 'rgba(139, 0, 0, 0.3)');
            gradient.addColorStop(0.7, 'rgba(75, 0, 130, 0.2)');
            gradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
            
            ctx.fillStyle = gradient;
            ctx.beginPath();
            ctx.arc(0, 0, this.aura.radius, 0, Math.PI * 2);
            ctx.fill();
            
            ctx.globalAlpha = 1;
        }
        
        drawUltimateBoss(ctx) {
            const halfSize = this.size / 2;
            
            // 生成动画
            if (this.state === 'spawning') {
                const spawnProgress = (Date.now() - this.spawnTime) / this.spawnDuration;
                ctx.globalAlpha = spawnProgress;
                const scale = spawnProgress;
                ctx.scale(scale, scale);
            }
            
            // 阶段转换特效
            if (this.phaseTransitionActive) {
                const progress = (Date.now() - this.phaseTransitionStartTime) / this.phaseTransitionDuration;
                const glow = Math.sin(progress * Math.PI * 6) * 0.5 + 0.5;
                ctx.shadowColor = '#FFD700';
                ctx.shadowBlur = 30 + glow * 20;
            }
            
            // 主体 - 病毒原始体
            const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, halfSize);
            gradient.addColorStop(0, '#4B0082');
            gradient.addColorStop(0.3, '#8B0000');
            gradient.addColorStop(0.7, '#2F1B69');
            gradient.addColorStop(1, '#000000');
            
            ctx.fillStyle = gradient;
            ctx.beginPath();
            ctx.arc(0, 0, halfSize, 0, Math.PI * 2);
            ctx.fill();
            
            // 恐怖的细节
            this.drawBossDetails(ctx, halfSize);
            
            // 血迹
            this.bloodStains.forEach(stain => {
                ctx.globalAlpha = stain.alpha;
                ctx.fillStyle = '#8B0000';
                ctx.fillRect(stain.x - stain.size/2, stain.y - stain.size/2, stain.size, stain.size);
            });
            
            ctx.globalAlpha = 1;
            ctx.shadowBlur = 0;
        }
        
        drawBossDetails(ctx, halfSize) {
            // 发光的眼睛（多只）
            for (let i = 0; i < 6; i++) {
                const angle = (Math.PI * 2 / 6) * i;
                const eyeX = Math.cos(angle) * halfSize * 0.6;
                const eyeY = Math.sin(angle) * halfSize * 0.6;
                
                ctx.fillStyle = '#FF0000';
                ctx.shadowColor = '#FF0000';
                ctx.shadowBlur = 10;
                ctx.beginPath();
                ctx.arc(eyeX, eyeY, 4, 0, Math.PI * 2);
                ctx.fill();
            }
            
            ctx.shadowBlur = 0;
            
            // 触手
            for (let i = 0; i < 8; i++) {
                const angle = (Math.PI * 2 / 8) * i + Date.now() * 0.002;
                const length = halfSize + 20 + Math.sin(Date.now() * 0.01 + i) * 10;
                
                ctx.strokeStyle = '#4B0082';
                ctx.lineWidth = 6;
                ctx.beginPath();
                ctx.moveTo(0, 0);
                ctx.lineTo(Math.cos(angle) * length, Math.sin(angle) * length);
                ctx.stroke();
            }
            
            // 中心核心
            ctx.fillStyle = '#FFD700';
            ctx.shadowColor = '#FFD700';
            ctx.shadowBlur = 15;
            ctx.beginPath();
            ctx.arc(0, 0, 8, 0, Math.PI * 2);
            ctx.fill();
            ctx.shadowBlur = 0;
        }
        
        drawBossHealthBar(ctx) {
            const barWidth = 120;
            const barHeight = 12;
            const halfSize = this.size / 2;
            const healthPercent = this.health / this.maxHealth;
            
            // 背景
            ctx.fillStyle = '#333333';
            ctx.fillRect(-barWidth/2, -halfSize - 30, barWidth, barHeight);
            
            // 血量（根据阶段变色）
            let healthColor = '#FF4500';
            if (this.phase >= 4) healthColor = '#8B0000';
            else if (this.phase >= 2) healthColor = '#DC143C';
            
            ctx.fillStyle = healthColor;
            ctx.fillRect(-barWidth/2, -halfSize - 30, barWidth * healthPercent, barHeight);
            
            // 边框
            ctx.strokeStyle = '#FFFFFF';
            ctx.lineWidth = 2;
            ctx.strokeRect(-barWidth/2, -halfSize - 30, barWidth, barHeight);
            
            // BOSS名称
            ctx.fillStyle = '#FFFFFF';
            ctx.font = 'bold 14px monospace';
            ctx.textAlign = 'center';
            ctx.fillText('病毒原始体', 0, -halfSize - 40);
        }
        
        drawPhaseIndicator(ctx) {
            const halfSize = this.size / 2;
            ctx.fillStyle = '#FFD700';
            ctx.font = 'bold 16px monospace';
            ctx.textAlign = 'center';
            
            let phaseText = `第${this.phase}阶段`;
            if (this.state === 'final_rage') {
                phaseText = '最终形态';
                ctx.fillStyle = '#FF0000';
            }
            
            ctx.fillText(phaseText, 0, halfSize + 30);
        }
        
        drawStatusEffects(ctx) {
            if (this.phaseTransitionActive) {
                ctx.fillStyle = '#FFD700';
                ctx.font = 'bold 12px monospace';
                ctx.textAlign = 'center';
                ctx.fillText('阶段转换中...', 0, -this.size/2 - 55);
            }
            
            // 当前攻击模式提示
            ctx.fillStyle = '#00FFFF';
            ctx.font = '10px monospace';
            ctx.fillText(this.currentAttackMode.replace('_', ' '), 0, this.size/2 + 45);
        }
    }
    
    // 终极BOSS投射物类
    class UltimateBossProjectile {
        constructor(x, y, vx, vy, damage, type = 'normal') {
            this.x = x;
            this.y = y;
            this.vx = vx;
            this.vy = vy;
            this.damage = damage;
            this.type = type;
            this.radius = type === 'barrage' ? 6 : 10;
            this.trail = [];
            this.maxTrailLength = 12;
            this.life = 5000;
            this.startTime = Date.now();
            
            // 根据类型设置颜色
            this.color = {
                'normal': '#FF4500',
                'barrage': '#8B0000',
                'homing': '#FFD700'
            }[type] || '#FF4500';
        }
        
        update(deltaTime) {
            // 添加拖尾
            this.trail.push({ x: this.x, y: this.y });
            if (this.trail.length > this.maxTrailLength) {
                this.trail.shift();
            }
            
            // 更新位置
            this.x += this.vx * deltaTime / 1000;
            this.y += this.vy * deltaTime / 1000;
            
            // 检查生命周期
            return Date.now() - this.startTime < this.life;
        }
        
        render(ctx) {
            ctx.save();
            
            // 绘制拖尾
            this.trail.forEach((point, index) => {
                const alpha = (index + 1) / this.trail.length * 0.8;
                ctx.globalAlpha = alpha;
                ctx.fillStyle = this.color;
                ctx.fillRect(point.x - 4, point.y - 4, 8, 8);
            });
            
            ctx.globalAlpha = 1;
            
            // 绘制投射物
            ctx.fillStyle = this.color;
            ctx.shadowColor = this.color;
            ctx.shadowBlur = 15;
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
            ctx.fill();
            
            ctx.restore();
        }
    }
    
    // 其他辅助类的简化版本...
    class UltimateBossClone {
        constructor(x, y, original) {
            this.x = x;
            this.y = y;
            this.original = original;
            this.health = Math.floor(original.maxHealth * 0.3);
            this.maxHealth = this.health;
            this.size = original.size * 0.7;
            this.damage = Math.floor(original.damage * 0.6);
            this.speed = original.speed * 1.2;
            this.life = 15000; // 15秒生命周期
            this.startTime = Date.now();
        }
        
        update(deltaTime, player) {
            // 简化的分身行为
            if (player && Date.now() - this.startTime < this.life) {
                // 朝玩家移动
                const dx = player.x - this.x;
                const dy = player.y - this.y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                
                if (distance > 0) {
                    const dirX = dx / distance;
                    const dirY = dy / distance;
                    
                    this.x += dirX * this.speed * deltaTime / 1000;
                    this.y += dirY * this.speed * deltaTime / 1000;
                }
                
                return true;
            }
            
            return false; // 分身消失
        }
        
        render(ctx) {
            ctx.save();
            ctx.globalAlpha = 0.7; // 半透明
            ctx.translate(this.x, this.y);
            
            // 简化的分身渲染
            ctx.fillStyle = '#9370DB';
            ctx.beginPath();
            ctx.arc(0, 0, this.size / 2, 0, Math.PI * 2);
            ctx.fill();
            
            ctx.restore();
        }
        
        takeDamage(damage) {
            this.health -= damage;
            return this.health <= 0;
        }
    }
    
    // 震波类
    class Shockwave {
        constructor(x, y, maxRadius, damage) {
            this.x = x;
            this.y = y;
            this.radius = 0;
            this.maxRadius = maxRadius;
            this.damage = damage;
            this.speed = 200; // 扩散速度
            this.startTime = Date.now();
            this.hasHitPlayer = false;
        }
        
        update(deltaTime) {
            this.radius += this.speed * deltaTime / 1000;
            
            // 检查与玩家的碰撞
            if (!this.hasHitPlayer && window.player) {
                const distance = Math.sqrt(
                    Math.pow(this.x - window.player.x, 2) + Math.pow(this.y - window.player.y, 2)
                );
                
                if (Math.abs(distance - this.radius) < 20) { // 震波厚度为20
                    window.player.takeDamage(this.damage);
                    this.hasHitPlayer = true;
                    console.log('⚡ 玩家被震波击中！');
                }
            }
            
            return this.radius < this.maxRadius;
        }
        
        render(ctx) {
            ctx.save();
            ctx.strokeStyle = '#FFD700';
            ctx.lineWidth = 8;
            ctx.globalAlpha = 1 - (this.radius / this.maxRadius);
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
            ctx.stroke();
            ctx.restore();
        }
    }
    
    // 流星类
    class Meteor {
        constructor(targetX, targetY, damage) {
            this.targetX = targetX;
            this.targetY = targetY;
            this.damage = damage;
            this.x = targetX + (Math.random() - 0.5) * 100;
            this.y = -50;
            this.vx = (targetX - this.x) * 0.01;
            this.vy = 200;
            this.radius = 15;
            this.trail = [];
            this.hasHit = false;
        }
        
        update(deltaTime) {
            if (this.hasHit) return false;
            
            this.trail.push({ x: this.x, y: this.y });
            if (this.trail.length > 10) {
                this.trail.shift();
            }
            
            this.x += this.vx * deltaTime / 1000;
            this.y += this.vy * deltaTime / 1000;
            
            // 检查是否到达目标
            if (this.y >= this.targetY) {
                this.explode();
                this.hasHit = true;
            }
            
            return !this.hasHit;
        }
        
        explode() {
            // 检查与玩家的距离
            if (window.player) {
                const distance = Math.sqrt(
                    Math.pow(this.targetX - window.player.x, 2) + Math.pow(this.targetY - window.player.y, 2)
                );
                
                if (distance < 60) { // 爆炸半径
                    window.player.takeDamage(this.damage);
                    console.log('☄️ 玩家被流星击中！');
                }
            }
            
            // 创建爆炸效果
            this.createExplosionEffect();
        }
        
        createExplosionEffect() {
            try {
                if (window.gameEngine && window.gameEngine.particles) {
                    for (let i = 0; i < 20; i++) {
                        const angle = (Math.PI * 2 * i) / 20;
                        const speed = Math.random() * 150 + 100;
                        
                        window.gameEngine.particles.push({
                            x: this.targetX,
                            y: this.targetY,
                            vx: Math.cos(angle) * speed,
                            vy: Math.sin(angle) * speed,
                            life: Math.random() * 2 + 1,
                            maxLife: Math.random() * 2 + 1,
                            color: ['#FF4500', '#FFD700', '#DC143C'][Math.floor(Math.random() * 3)],
                            size: Math.random() * 8 + 4
                        });
                    }
                }
            } catch (error) {
                console.error('创建流星爆炸效果失败:', error);
            }
        }
        
        render(ctx) {
            ctx.save();
            
            // 绘制拖尾
            this.trail.forEach((point, index) => {
                const alpha = (index + 1) / this.trail.length * 0.8;
                ctx.globalAlpha = alpha;
                ctx.fillStyle = '#FF4500';
                ctx.fillRect(point.x - 5, point.y - 5, 10, 10);
            });
            
            ctx.globalAlpha = 1;
            
            // 绘制流星
            ctx.fillStyle = '#FFD700';
            ctx.shadowColor = '#FFD700';
            ctx.shadowBlur = 20;
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
            ctx.fill();
            
            ctx.restore();
        }
    }
    
    // 环境效果类
    class EnvironmentEffect {
        constructor(x, y, type, duration) {
            this.x = x;
            this.y = y;
            this.type = type;
            this.duration = duration;
            this.startTime = Date.now();
            this.radius = 80;
            this.intensity = 1.0;
        }
        
        update(deltaTime) {
            const elapsed = Date.now() - this.startTime;
            
            // 检查与玩家的交互
            if (window.player) {
                const distance = Math.sqrt(
                    Math.pow(this.x - window.player.x, 2) + Math.pow(this.y - window.player.y, 2)
                );
                
                if (distance < this.radius) {
                    this.affectPlayer(window.player);
                }
            }
            
            return elapsed < this.duration;
        }
        
        affectPlayer(player) {
            switch (this.type) {
                case 'poison_cloud':
                    if (Math.random() < 0.02) { // 2%概率每帧
                        player.takeDamage(1);
                    }
                    break;
                case 'electric_field':
                    if (Math.random() < 0.01) { // 1%概率每帧
                        player.takeDamage(3);
                    }
                    break;
                // 其他效果...
            }
        }
        
        render(ctx) {
            ctx.save();
            
            const alpha = Math.sin(Date.now() * 0.005) * 0.3 + 0.5;
            ctx.globalAlpha = alpha;
            
            let color = '#800080';
            switch (this.type) {
                case 'poison_cloud':
                    color = '#228B22';
                    break;
                case 'electric_field':
                    color = '#00FFFF';
                    break;
                case 'gravity_well':
                    color = '#4B0082';
                    break;
                case 'time_distortion':
                    color = '#FFD700';
                    break;
            }
            
            ctx.strokeStyle = color;
            ctx.lineWidth = 4;
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
            ctx.stroke();
            
            ctx.restore();
        }
    }
    
    // 将UltimateBoss导出到全局
    window.UltimateBoss = UltimateBoss;
    window.UltimateBossProjectile = UltimateBossProjectile;
    window.UltimateBossClone = UltimateBossClone;
    window.Shockwave = Shockwave;
    window.Meteor = Meteor;
    window.EnvironmentEffect = EnvironmentEffect;
    
    console.log('✅ 终极BOSS系统已加载');
    
})();